<script setup lang="ts">
import { Message } from '@arco-design/web-vue'
import dayjs from 'dayjs'
import { getCdnGroupListApi, getCdnNodeListApi } from '@/apis/modules/cdn'
import { CdnNodeStatusOptions } from '@/constants/cdn-node'
import { commonTableProps, defaultRowSelection } from '@/utils/table'
import useCommand from './actions'
import AddNode from './components/AddNode.vue'
import useConfig from './useConfig.ts'

const router = useRouter()
const queryParams = ref({ group_id: '', run_status: '' })

const { searchSchema, tableColumns } = useConfig()

const { visible: dialogVisible, open: openEditDialog }
  = usePopup<MachineGroup>()

// const {
//   selectedKeys,
//   data: tableData,
//   loading,
//   pagination,
//   run,
// } = useListRequest(getCdnNodeListApi, {
//   params: queryParams,
//   immediate: true,
// })
const {
  data: tableData,
  pagination,
  loading,
  run,
} = useListRequest(getCdnNodeListApi, {
  immediate: true,
  params: queryParams,
})

const { tableRef, selectedKeys, selectionRows } = useTable(run, tableData)

function batchSetTag() {
  const data
    = selectionRows.value.map(item => ({
      id: item.id,
      group_id: item.cluster_id,
    })) ?? []
}

function toManagement(row: NodeListItem) {
  // if (row.installed) {
  //   router.push({ name: 'CdnNodeNodeManagement', params: { id: row.id } })
  // }
  if (row.status !== 5) {
    router.push({ name: 'CdnNodeNodeManagement', params: { id: row.id } })
  }
}
// function toDetailPage(id: string) {
//   router.push({ name: 'DevOpsMonitorTaskDetails', params: { id } })
// }
const { copy } = useClipboard({
  legacy: true,
})
function handleCopy(content: string) {
  copy(String(content)).then(() => {
    Message.success('复制成功')
  })
}

function isPlatform(
  platform: string | undefined,
  targetPlatform: string,
): boolean {
  return platform?.toUpperCase() === targetPlatform.toUpperCase()
}

const { handleCommand } = useCommand(run)
const ClusterOptions = ref<LabelValue[]>([])
// 获取集群列表
async function getGroupList() {
  const res = await getCdnGroupListApi({ limit: 0 })
  const list = res.list ?? []

  ClusterOptions.value = list
    .map(item => ({ label: item.name!, value: item.id! }))
    .filter(Boolean)
}

onMounted(() => {
  getGroupList()
})

const typeOptions = [
  {
    label: '异常',
    value: 0,
  },
  {
    label: '正常',
    value: 1,
  },
  {
    label: '停止',
    value: 2,
  },
  {
    label: '离线',
    value: 3,
  },
]

const statusColorMap = {
  0: 'text-[#FF7D00]!',
  1: 'text-[#00A65B]!',
  2: 'text-[#1D2129]!',
  3: 'text-[#FA5566]!',
}
</script>

<template>
  <main-container
    v-model:pagination="pagination"
    :loading="loading"
    @run="run"
  >
    <template #header>
      <a-button
        type="primary"
        @click="openEditDialog()"
      >
        新建节点
      </a-button>
      <a-select
        v-model="queryParams.group_id"
        class="!w-160px"
        placeholder="全部节点分组"
        :options="[{ label: '全部节点分组', value: '' }, ...ClusterOptions]"
        @change="run()"
      />
      <a-select
        v-model="queryParams.run_status"
        class="!w-160px"
        placeholder="全部运行状态"
        :options="[
          { label: '全部运行状态', value: '' },
          ...CdnNodeStatusOptions,
        ]"
        @change="run()"
      />

      <multiple-condition-search
        v-model="queryParams"
        :schema="searchSchema"
        style="height: 32px"
        @search="run"
      />
    </template>
    <a-table
      v-bind="commonTableProps"
      ref="tableRef"
      v-model:selected-keys="selectedKeys"
      :columns="tableColumns"
      :data="tableData"
      :row-selection="defaultRowSelection"
    >
      <template #cluster_name="{ record }">
        {{ record.group?.name || '-' }}
      </template>
      <template #name="{ record }">
        <!-- <span
          class="cursor-pointer"
          :class="{ 'text-primary': record.installed }"
          @click="toManagement(record)"
          >{{ record.name || '-' }}</span
        > -->
        <div>
          <text-ell
            v-if="!record.installed"
            class="text-[#ADAFB2]"
          >
            {{ record.name || '-' }}
          </text-ell>
          <text-ell
            v-else
            class="cursor-pointer text-[#1D2129]"
            @click="toManagement(record)"
          >
            <div class="table-link-text">
              {{ record.name || '-' }}
            </div>
          </text-ell>
          <!-- <span v-if="!record.installed" class="text-[#ADAFB2]">{{
            record.name || '-'
          }}</span>
          <div
            v-else
            class="text-[#1D2129] cursor-pointer table-link-text"
            @click="toManagement(record)">
            {{ record.name || '-' }}
          </div> -->
        </div>
      </template>

      <template #ip="{ record }">
        <div
          v-if="record.ips.filter(Boolean).length > 0"
          class="flex items-center gap-x-1"
        >
          <span>{{ record.ips[0] }} </span>
          <!-- <a-popover v-if="record.ips.length > 1">
            <i-icons-base-info
              class="table-icon text-7 hover:text-2 cursor-pointer ml-2 flex-shrink-0" />
            <template #content>
              <div class="text-1 font-bold">IP</div>
              <template v-for="(ip, index) in record.ips" :key="ip">
                <div v-if="index === 0" class="flex items-center gap-x-2">
                  <span>{{ ip }}(主)</span>
                  <i-icons-copy
                    class="text-7 hover:text-2 cursor-pointer"
                    @click="handleCopy(ip)" />
                </div>
                <CopyField v-else display>{{ ip }}</CopyField>
              </template>
  </template>
  </a-popover> -->
        </div>
        <span v-else>-</span>
      </template>
      <template #status="{ record }">
        <div
          v-if="Number(record.status?.run_status) > 0"
          class="common-box"
        >
          <a-popover
            trigger="hover"
            position="right"
            :content-style="{ padding: '8px 4px' }"
          >
            <template #content>
              <div class="node-status-box">
                <div class="node-status-th">
                  <div class="node-status-key">
                    ATS
                  </div>
                  <div
                    class="node-status-value"
                    :class="
                      statusColorMap[record.status?.service_status?.ats_status]
                    "
                  >
                    {{
                      getOptionsLabel(
                        typeOptions,
                        record.status?.service_status?.ats_status,
                      )
                    }}
                  </div>
                </div>
                <div class="node-status-th">
                  <div class="node-status-key">
                    OpenResty
                  </div>
                  <div
                    class="node-status-value"
                    :class="
                      statusColorMap[
                        record.status?.service_status?.openresty_status
                      ]
                    "
                  >
                    {{
                      getOptionsLabel(
                        typeOptions,
                        record.status?.service_status?.openresty_status,
                      )
                    }}
                  </div>
                </div>
                <div class="node-status-th">
                  <div class="node-status-key">
                    Agent
                  </div>
                  <div
                    class="node-status-value"
                    :class="
                      statusColorMap[
                        record.status?.service_status?.agent_status
                      ]
                    "
                  >
                    {{
                      getOptionsLabel(
                        typeOptions,
                        record.status?.service_status?.agent_status,
                      )
                    }}
                  </div>
                </div>
                <div class="node-status-th">
                  <div class="node-status-key">
                    上次探测时间
                  </div>
                  <div class="node-status-value">
                    {{
                      dayjs(
                        record.status?.service_status?.last_check_at * 1000,
                      ).format('YYYY-MM-DD HH:mm:ss')
                    }}
                  </div>
                </div>
              </div>
            </template>
            <!-- <i-icons-node-normal
              v-if="
                record.status?.service_status?.ats_status === 1
                  && record.status?.service_status?.openresty_status === 1
                  && record.status?.service_status?.agent_status === 1
              "
            />
            <i-icons-warning
              v-if="
                ((record.status?.service_status?.ats_status === 1 && record.status?.service_status?.openresty_status === 2)
                  || (record.status?.service_status?.ats_status === 2 && record.status?.service_status?.openresty_status === 1))
                  && record.status?.service_status?.agent_status === 1
              "
            />
            <i-icons-node-stop
              v-if="
                record.status?.service_status?.ats_status === 2
                  && record.status?.service_status?.openresty_status === 2
                  && record.status?.service_status?.agent_status === 1"
            />
            <i-icons-failed v-if="record.status?.service_status?.agent_status === 0" /> -->
            <i-icons-node-normal v-if="record.status?.run_status === 1" />
            <i-icons-warning v-if="record.status?.run_status === 2" />
            <i-icons-node-stop v-if="record.status?.run_status === 3" />
            <i-icons-failed v-if="record.status?.run_status === 4" />
          </a-popover>
          <!-- <i-icons-node-init v-if="record.status?.service_status?.agent_status === 5" /> -->
          <i-icons-node-init v-if="record.status?.run_status === 5" />
          <span class="ml-1">{{
            getOptionsLabel(CdnNodeStatusOptions, record.status?.run_status)
          }}</span>
          <a-dropdown
            v-if="record.status?.run_status !== 5"
            content-class="table-dropdown"
            @select="v => handleCommand(v as string, [record.id], record)"
          >
            <i-icons-more-action class="table-icon" />
            <template #content>
              <div class="px-1">
                <a-doption
                  style="width: 80px"
                  class="rounded-[4px]"
                  value="startOne"
                  :disabled="record.status?.run_status === 1"
                >
                  启用
                </a-doption>
                <a-doption
                  value="stopOne"
                  class="rounded-[4px]"
                  :disabled="record.status?.run_status === 3"
                >
                  停止
                </a-doption>
                <a-doption
                  value="reloadOne"
                  class="rounded-[4px]"
                >
                  重启
                </a-doption>
              </div>
            </template>
          </a-dropdown>
        </div>
        <span v-else>-</span>
      </template>

      <template #resolve_status="{ record }">
        <div
          v-if="record.group?.type === 1"
          class="common-box"
        >
          <span
            :class="
              record.status?.resolve_status === 1
                ? 'text-#1D2129'
                : 'text-#86909C'
            "
          >
            {{ record.status?.resolve_status === 1 ? '已解析' : '未解析' }}
          </span>
          <a-dropdown
            v-if="record.installed && record.status?.run_status !== 5"
            content-class="table-dropdown"
            @select="v => handleCommand(v as string, [record.id], record)"
          >
            <i-icons-more-action class="table-icon" />
            <template #content>
              <div class="px-1">
                <a-doption
                  value="join"
                  class="rounded-[4px]"
                  :disabled="Number(record.status?.resolve_status) === 1"
                >
                  加入解析
                </a-doption>
                <a-doption
                  value="remove"
                  class="rounded-[4px]"
                  :disabled="Number(record.status?.resolve_status) !== 1"
                >
                  移除解析
                </a-doption>
              </div>
            </template>
          </a-dropdown>
        </div>
        <div v-else>
          -
        </div>
      </template>

      <template #version="{ record }">
        <div class="common-box gap-x-0!">
          <span>{{ record?.status?.service_status?.version || '-' }}</span>

          <i-icons-upgrade
            v-if="
              !record.is_latest_version
                && record?.status?.service_status?.version
            "
            class="cursor-pointer"
            @click="handleCommand('version', [record.id], record)"
          />
          <!-- <i-icons-change v-if="record.version" class="table-icon ml-6px"
            @click="handleCommand('version', [record.id], record)" /> -->
        </div>
      </template>

      <template #os="{ record }">
        <a-tooltip
          v-if="record.platform"
          :show-arrow="false"
        >
          <i-icons-ubuntu
            v-if="isPlatform(record.platform, 'ubuntu')"
            class="h-6! w-6!"
          />
          <i-icons-centos
            v-else-if="isPlatform(record.platform, 'centos')"
            class="h-6! w-6!"
          />
          <i-icons-debian
            v-else-if="isPlatform(record.platform, 'debian')"
            class="h-6! w-6!"
          />
          <i-icons-rocky-linux
            v-else-if="isPlatform(record.platform, 'rocky')"
            class="h-6! w-6!"
          />
          <i-icons-unix
            v-else
            class="h-6! w-6!"
          />
          <template #content>
            {{ record.platform }} {{ record.platform_version || '' }}
          </template>
        </a-tooltip>
        <span v-else>-</span>
      </template>
      <template #action="{ record }">
        <!-- <a-link
          :hoverable="false"
          @click="toManagement(record)"
        >
          管理
        </a-link>

        <a-link
          :hoverable="false"
          status="danger"
          @click="handleCommand('delete', [record.id], record)"
        >
          删除
        </a-link> -->
        <a-link
          v-if="record.installed"
          :hoverable="false"
        >
          <i-icons-edit
            size="16px"
            :class="record.status === 5 ? 'cursor-not-allowed opacity-60' : ''"
            @click="toManagement(record)"
          />
        </a-link>
        <a-link
          v-else
          :hoverable="false"
          @click="handleCommand('install_script', [record.id])"
        >
          <i-icons-install size="16px" />
        </a-link>
        <a-link
          :hoverable="false"
          :disabled="record.node_count > 0"
          status="danger"
          @click="handleCommand('delete', [record.id], record)"
        >
          <i-icons-delete size="16px" />
        </a-link>
      </template>
    </a-table>

    <template
      v-if="selectedKeys.length > 0"
      #total
    >
      <div class="flex-shrink-0">
        <!-- <a-button
          type="outline"
          class="mr-2"
          @click="batchSetTag"
        >
          启动
        </a-button> -->
        <a-button
          type="outline"
          class="mr-2"
          @click="handleCommand('start', selectedKeys as string[])"
        >
          启用
        </a-button>
        <a-button
          type="outline"
          class="mr-2"
          @click="handleCommand('reload', selectedKeys as string[])"
        >
          重启
        </a-button>
        <!-- <a-button
          type="outline"
          class="mr-2"
          @click="handleCommand('stop', selectedKeys as string[])"
        >
          停用
        </a-button> -->
        <a-dropdown
          @select="
            v =>
              handleCommand(
                v as string,
                selectedKeys as string[],
                selectionRows[0],
              )
          "
        >
          <a-button
            class="mr-2"
            type="outline"
          >
            更多
            <!-- <IconDown /> -->
          </a-button>
          <template #content>
            <div class="px-1">
              <a-doption
                value="stop"
                class="rounded-[4px]"
              >
                停止
              </a-doption>
              <a-doption
                value="config"
                class="rounded-[8px]"
              >
                同步配置
              </a-doption>
              <a-doption
                value="cache"
                class="rounded-[4px]"
              >
                清理缓存
              </a-doption>
              <a-doption
                value="version"
                class="rounded-[4px]"
              >
                升级版本
              </a-doption>
            </div>
          </template>
        </a-dropdown>
        <span class="text-color-3">{{ `已选${selectedKeys.length}条` }}</span>
      </div>
    </template>
  </main-container>
  <add-node
    v-model:visible="dialogVisible"
    @reload="run"
  />
</template>

<style lang="less" scoped>
.common-box {
  display: flex;
  align-items: center;
  gap: 4px;
}

// .question-icon {
//   color: #86909c;
//   width: 14px !important;
//   height: 14px !important;
//   cursor: pointer;

//   &:hover {
//     color: #00a65b;
//   }
// }

:deep(.arco-table-tr) {
  .table-icon {
    opacity: 0;
    color: var(--color-text-7);
    cursor: pointer;
  }

  &:hover {
    .table-copy-text {
      @apply text-primary;
    }

    .table-icon {
      opacity: 1;
      color: #00a65b;
    }
  }
}

.node-status-box {
  display: flex;
  padding: 0 8px;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  gap: 4px;
  align-self: stretch;

  .node-status-th {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;

    .node-status-key {
      color: var(--text-3, #86909c);
      font-size: 12px;
      line-height: 20px;
      width: 72px;
    }

    .node-status-value {
      color: var(--text-2, #4e5969);
      font-size: 12px;
      line-height: 20px;
      /* 166.667% */
    }
  }
}
</style>
